15. Stream API: Collectors
Stream API: Collectors
In this section, you will learn to collect streams into other kinds of data structures.
ND079 JPND C2 L01 A12 Stream API Collectors
What is a Collector?
A Collector
is a terminal stream operation that accumulates stream elements into a container.
Collector
Code Examples
The collect()
method is a terminal operation that aggregates streams of elements. Collectors can be passed to collect()
to determine what kind of collection is created.
Set<String> s = stringList.stream().collect(Collectors.toSet());
Here, the collector aggregates the elements into a Set
. There are collectors for all the common data structures such as lists, sets, and maps.
Collectors can be used to perform reduction operations such as adding or counting.
Map<Year, Long> graduatingClassSizes = studentList.stream()
.collect(Collectors.groupingBy(
Student::getGraduationYear, Collectors.counting());
Here, groupingBy()
is used to collect elements into a Map
. Collectors.counting()
counts the number of values for each key, so, in this example, it will count how many students there are for each graduation year.
SOLUTION:
- Aggregating stream elements into a data structure such as list, a map or a set.
- Performing reduction operations like summing or counting elements.